package cn.nxcoder.blog.listener;

import cn.nxcoder.blog.entity.Blog;
import cn.nxcoder.blog.entity.Tag;
import cn.nxcoder.blog.entity.Type;
import cn.nxcoder.blog.service.BlogService;
import cn.nxcoder.blog.service.TagService;
import cn.nxcoder.blog.service.TypeService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

import javax.servlet.ServletContext;
import java.util.List;

/**
 * @author shengwu ni
 */
@Component
public class InitListener implements ApplicationListener<ContextRefreshedEvent> {


    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {

        ApplicationContext applicationContext = contextRefreshedEvent.getApplicationContext();
        BlogService blogService = applicationContext.getBean(BlogService.class);
        TypeService typeService = applicationContext.getBean(TypeService.class);
        TagService tagService = applicationContext.getBean(TagService.class);
        // 查询出6条博客类型数据（按照包含博客数量多少降序）
        List<Type> typeList = typeService.findAllTypes();
        // 查询出10条博客标签数据（按照包含博客数量多少降序）
        List<Tag> tagList = tagService.findAllTags();
        // 查询出访问量最多的5条记录
        List<Blog> topView = blogService.findTop5Views();

        ServletContext application = applicationContext.getBean(ServletContext.class);
        application.setAttribute("types", typeList);
        application.setAttribute("tags", tagList);
        application.setAttribute("views", topView);
        application.setAttribute("total", blogService.findAll().size());
    }

}
